<!DOCTYPE html>
<html lang="zh-Hans-CN">
<head>
  <% include("/include/header3.html",{"title":"开发-站内消息编辑页","tinymce":true}){} %>
</head>
<body>

<div id="app">
  <div class="mainBox ">
    <div class="main-container layui-card">
      <div class="layui-card-body py-50">

         <t-form ref="formRef" :data="form" :rules="rules" :disabled="loading || form.status === 1" scroll-to-first-error="smooth" colon requiredMark>
           <t-row :gutter="[50,20]">
            <t-col :span="12">
              <t-form-item label="消息标题" name="title">
                <t-input v-model="form.title" placeholder="请输入消息标题" :maxlength="255" show-limit-number clearable></t-input>
              </t-form-item>
            </t-col>
             <t-col :xs="12" :sm="6">
              <t-form-item label="通知全部" name="whole">
                <t-radio-group v-model="form.whole" @change="changeWhole">
                  <t-radio label="全部" :value="1"></t-radio>
                  <t-radio label="用户" :value="2"></t-radio>
                </t-radio-group>
              </t-form-item>
            </t-col>
            <t-col v-if="form.whole === 2" :xs="12" :sm="6">
              <t-form-item label="消息类型" name="category">
                <t-select v-model="form.category" :loading="categoryOptions.loading" :options="categoryOptions.data" placeholder="请选择消息类型" clearable></t-select>
              </t-form-item>
            </t-col>
            <t-col v-if="form.whole === 2" :span="12">
              <t-form-item label="用户列表" name="userList">
                <t-space>
                  <t-tag v-for="(item,index) in userList" :key="item.id" theme="primary" size="large" :closable="form.status == 0" @close="deselect(index)">{{parseContent(item)}}</t-tag>
                  <t-button v-if="form.status === 0" theme="default" @click="openSelUser">选择用户</t-button>
                </t-space>
              </t-form-item>
            </t-col>
            <t-col :span="12">
              <t-form-item label="消息正文" name="content">
                <textarea v-model="form.content" class="layui-textarea" id="contentEditor" name="content" :readonly="form.status === 1" placeholder="请输入公告内容"></textarea>
              </t-form-item>
            </t-col>
          </t-row>
        </t-form>

      </div>
    </div>
  </div>
  <div class="bottom">
    <t-space class="button-container ">
      <t-button v-if="form.status === 0" :loading="loading" theme="primary" @click="onSave"><i class="layui-icon layui-icon-ok mr-5 text-size-14"></i>保存</t-button>
      <t-button v-if="form.id && form.status === 0" :loading="loading" theme="primary" @click="clickRelease">
        <i class="layui-icon layui-icon-ok mr-5 text-size-14"></i>发布</t-button>
      <t-button theme="warning" @click="closeBtn.close"><i class="layui-icon mr-5 text-size-14" :class="closeBtn.i"></i>{{closeBtn.t}}</t-button>
    </t-space>
  </div>
</div>

<script>
  const PATH_URL = "dev/message/";
</script>

<script>

  setupVue("#app", {
    setup() {
      const ID = getLayerData("id") || "${id!''}";

      // 初始化编辑器
      let EDITOR;
      tinymceInit("#contentEditor", (editor) => {
        EDITOR = editor;
        if (ID) getForm(ID);
        else loading.value = false;
      }, { height: "700px", baseDir: "dev/message" });

      // 表单相关
      const loading = Vue.ref(true);
      const formRef = Vue.ref(null);
      const form = Vue.ref({
        category: null,
        title: null,
        content: null,
        whole: 1,
        status: 0,
        extJson: null,
        publishTime: null,
      });
      const rules = {
        category: [$required('请选择消息类型')],
        title: [$required('请输入消息标题')],
        userList: [$required('请选择用户')],
        content: [$required('请输入消息正文')],
        whole: [$required('请选择是否通知全部')],
      };
      // 获取表单数据
      const getForm = (id) => req(axiosGet, PATH_URL + "getInfo", { id }, (res) => {
        if (res.code === 200) {
          form.value = res.data;
          if (form.value.userList) {
            userList.value = JSON.parse($base.deepClone(form.value.userList));
          }
          EDITOR.setContent(res.data.content);
          if (form.value.status === 1) {
            EDITOR.getBody().setAttribute("contenteditable", "false");
          }
          startWatch();
        } else {
          $baseAlert(res.msg, () => closeBtn.value.close());
        }
      }, loading);

      // 启动监听器
      let formMidify = false;
      const startWatch = () => {
        formMidify = false;
        const watch = Vue.watch(form.value, (data) => {
          formMidify = true;
          watch(); // 停止
        });
      }

      // 点击保存
      const onSave = () => {
        form.value.content = EDITOR.getContent();
        console.log(form.value)
        formRef.value.validate().then((validateResult) => {
          if (validateResult && Object.keys(validateResult).length) {
            const firstError = Object.values(validateResult)[0]?.[0]?.message;
            $baseMsg(firstError);
          } else {
            let REQ;
            let URL;
            if (form.value.id) {
              REQ = axiosPut, URL = PATH_URL + "update";
            } else {
              REQ = axiosPost, URL = PATH_URL + "add";
            }
            req(REQ, URL, form, (res) => {
              $baseAlert(res.msg, () => {
                if (res.code === 200) {
                  form.value.id = res.data;
                  startWatch();
                }
              })
            }, loading);
          }
        });
      }

      // 消息类型
      const categoryOptions = useOptions();
      dictOptions({ columnField: "label,value", codeLike: "dev_message_category_" }, categoryOptions);

      const changeWhole = () => {
        if (form.value.whole === 1) {
          form.value.category = "系统通知";
        } else {
          form.value.category = "";
        }
      }

      // 选择发送的用户
      // 用户列表
      const userList = Vue.ref([]);
      const openSelUser = () => {
        let list = [];
        userList.value.forEach(v => {
          list.push({ id: v.receiverId, name: v.receiverName });
        })
        openLayer({
          parent: true,
          area: ['1200px', '750px'],
          content: "sys/user/sel",
          data: {
            userList: list,
            success: (rows) => {
              buildUserList(rows);
            },
          },
        })
      }
      // 取消选择
      const deselect = (index) => {
        userList.value.splice(index, 1);
        setFormUserList();
      }

      const buildUserList = (rows) => {
        userList.value = [];
        rows.forEach(v => {
          userList.value.push({ receiverId: v.id, receiverName: v.name });
        })
        setFormUserList();
      }
      const setFormUserList = () => {
        if (userList.value.length === 0) {
          form.value.userList = "";
        } else {
          form.value.userList = JSON.stringify(userList.value);
        }
      }

      // 展示用户名称
      const parseContent = (item) => {
        let name = item.receiverName;
        if (form.value.status === 1) {
          switch (item.messageStatus) {
            case 0:
              name += "（未读）";
              break;
            case 1:
              name += "（已读）";
              break;
            case 9:
              name += "（删除）";
              break;
            default:
              name += "（未知）";
              break;
          }
        }
        return name;
      }

      // 点击发布
      const clickRelease = () => {
        form.value.content = EDITOR.getContent();
        formRef.value.validate().then((validateResult) => {
          if (validateResult && Object.keys(validateResult).length) {
            const firstError = Object.values(validateResult)[0]?.[0]?.message;
            $baseMsg(firstError);
          } else {
            if (formMidify) {
              $baseConfirm("检测到您已修改内容，是否保存并发布？", {
                btn: ["保存并发布", "只发布", "取消"],
                btn3: function (index) {
                  layer.close(index);
                },
              }, async () => {
                await onSave();
                release();
              }, () => {
                release();
              })
            } else {
              $baseConfirm("确定发布该消息吗？", () => {
                release();
              })
            }
          }
        });
      };

      // 发布消息
      const release = () => {
        req(axiosPut, PATH_URL + "release", { id: form.value.id }, (res) => {
          if (res.code === 200) {
            form.value.status = 1;
            closeBtn.value.close();
          } else {
            $baseAlert(res.msg);
          }
        }, loading)
      }

      const closeBtn = useCloseBtn();
      return {
        formRef, loading, form, rules,
        onSave, clickRelease, closeBtn,
        categoryOptions, changeWhole,
        userList, deselect, openSelUser, parseContent,
      }

    },
  });
</script>


</body>
</html>
